<template>
<view class="personal-center">
    <!-- 添加调试信息 -->

    
    <!-- 头像和昵称区域 -->
    <view class="profile-section">
      <image 
        class="avatar" 
        :src="isLoggedIn ? imgurl || '/static/tu3.jpg' : '/static/tu3.jpg'"
        @click="handleAvatarClick"
        mode="aspectFill"
        @error="handleAvatarError"
      />
      <text class="nickname" @click="handleLoginClick">
        {{ isLoggedIn ? nusername : '点击登录' }}
      </text>
    </view>

    <!-- 九宫格区域 -->
    <view class="grid-section">
      <view 
        class="grid-item" 
        v-for="(item, index) in gridItems" 
        :key="index" 
        @click="onGridItemClick(item)"
      >
        <image :src="item.icon" class="grid-icon" />
        <text class="grid-text">{{ item.text }}</text>
      </view>
    </view>

    <!-- 文章列表 -->
    <view class="article-list">
      <view v-if="!isLoggedIn" class="no-login-tip">
        登录后查看您发布的内容
      </view>
      <view v-else-if="articles.length === 0" class="empty-tip">
        暂无发布的内容
      </view>
      <view v-else class="article-item" v-for="article in articles" :key="article.id" @click="handleArticleClick(article)">
        <!-- 文章内容 -->
        <view class="article-content">
          <!-- 添加删除按钮和文章标题的容器 -->
          <view class="article-header">
            <view class="article-text">{{ article.content }}</view>
            <!-- 删除按钮 -->
            <view 
              class="delete-article-btn" 
              @tap.stop="handleDeleteArticle(article.id)"
            >
              删除
            </view>
          </view>
          
          <!-- 图片内容 -->
          <view class="article-images" v-if="article.images && article.images.length">
            <image v-if="article.images.length === 1" 
                   class="single-image" 
                   :src="article.images[0]" 
                   mode="widthFix"
                   @error="handleImageError"
                   :data-index="index"
                   @click.stop="previewImage(article.images, 0)"/>
            <view v-else class="image-grid">
              <image v-for="(img, imgIndex) in article.images" 
                     :key="imgIndex" 
                     :src="img" 
                     mode="aspectFill"
                     @error="handleImageError"
                     :data-index="imgIndex"
                     style="width: 200rpx; height: 200rpx;"
                     @click.stop="previewImage(article.images, imgIndex)"/>
            </view>
          </view>
        </view>
        
        <!-- 发布时间和互动信息 -->
        <view class="article-footer">
          <view class="post-time">{{ article.postTime }}</view>
          <view class="article-actions">
            <view class="action-item">
              <image src="/static/like.png"></image>
              <text>{{ article.likes || 0 }}</text>
            </view>
            <view class="action-item">
              <image src="/static/comment.png"></image>
              <text>{{ article.comments || 0 }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
</view>
</template>

<script>
import tool from '@/utils/tool.js'
import authApi from '@/api/authApi.js'
import postApi from '@/api/postApi.js'

export default {
  data() {
    return {
      title: 'Hello',
      imgurl: '',
      nusername: '',
      loading: true,
      isLoggedIn: false,
      articles: [],
      gridItems: [
        { text: '我的点赞', icon: '/static/点赞.png', path: '' },
        { text: '我的勋章', icon: '/static/头衔.png', path: '/pages/mine/Decoration' },
        { text: '社团入驻', icon: '/static/社团.png', path: '/pages/mine/club' },
        { text: '反馈建议', icon: '/static/反馈建议.png', path: '' }
      ],
      userId: ''
    }
  },

  onLoad() {
    this.checkLoginStatus()
  },

  onShow() {
    this.checkLoginStatus()
  },

  methods: {
    checkLoginStatus() {
      // 先检查全局状态
      const app = getApp()
      if (app.globalData && app.globalData.isLoggedIn && app.globalData.userInfo) {
        this.isLoggedIn = true
        this.imgurl = app.globalData.userInfo.imgurl
        this.nusername = app.globalData.userInfo.username
        this.userId = app.globalData.userInfo.userId
        this.getUserArticles()
        return
      }
      
      // 如果全局状态不存在，则检查本地存储
      const token = tool.data.get('token')
      const storedImgUrl = tool.data.get('imgurl')
      const storedUsername = tool.data.get('username')
      const storedUserId = tool.data.get('userId')
      
      if (token && storedUsername) {
        this.isLoggedIn = true
        this.imgurl = storedImgUrl
        this.nusername = storedUsername
        this.userId = storedUserId
        
        // 同步更新全局状态
        if (app.globalData) {
          app.globalData.isLoggedIn = true
          app.globalData.userInfo = {
            token,
            username: storedUsername,
            imgurl: storedImgUrl,
            userId: storedUserId
          }
        }
        
        this.getUserArticles()
      } else {
        this.isLoggedIn = false
        this.imgurl = '/static/avatar.png'
        this.nusername = ''
        this.userId = ''
        this.articles = []
      }
    },

    handleAvatarClick() {
      if (this.isLoggedIn) {
        uni.navigateTo({
          url: '/pages/mine/user-space',
          success: () => {
            tool.data.set('imgurl', this.imgurl)
            tool.data.set('username', this.nusername)
          }
        })
      } else {
        this.getUserInfo()
      }
    },

    handleLoginClick() {
      if (!this.isLoggedIn) {
        this.getUserInfo()
      }
    },
    getUserInfo() {
      uni.getUserProfile({
        desc: '用于个人学习',
        success: info => {
          console.log("info:", info)
          this.getToken(info)
        },
        fail: (err) => {
          console.log("err:", err)
          if (err.errMsg === "getUserProfile:fail auth deny") {
            uni.showToast({
              title: '您取消了登录授权！',
              icon: 'none'
            })
          }
        }
      })
    },

    getToken(info) {
      const query = {
        code: "",
        username: info.userInfo.nickName,
        haedPortrait: info.userInfo.avatarUrl
      }

      uni.login({
        provider: 'weixin',
        success: res => {
          if (res.errMsg === 'login:ok') {
            query.code = res.code
            authApi.login(query).then(res => {
            
              
              // 使用后端返回的头像URL
              let avatarUrl = res.data.haedPortrait
    
              
              if (!avatarUrl) {
                console.error('后端未返回头像URL')
                avatarUrl = '/static/tu3.jpg' // 使用已存在的默认图片
              }
              
              // 更新头像URL
              this.imgurl = avatarUrl
              tool.data.set('imgurl', avatarUrl)
                 tool.data.set('token', res.data.jwt)
              // 存储和更新其他状态
              tool.data.set('username', res.data.username)
              tool.data.set('userId', res.data.id)
                 this.nusername = res.data.username
              this.nusername = res.data.username
              this.isLoggedIn = true
              this.userId = res.data.id
              
              // 更新全局状态
              const app = getApp()
              if (app.globalData) {
                app.globalData.isLoggedIn = true
                app.globalData.userInfo = {
                  token: res.data.jwt,
                  username: res.data.username,
                  imgurl: avatarUrl,
                  userId: res.data.id
                }
              }
              
        
              
              this.getUserArticles()
              
              uni.showToast({
                title: '登录成功',
                icon: 'success'
              })
            }).catch(err => {
              console.error('登录失败:', err)
              uni.showToast({
                title: '登录失败，请重试',
                icon: 'none'
              })
            })
          }
        }
      })
    },

    previewImage(images, current) {
      uni.previewImage({
        urls: images,
        current: current
      })
    },

    handleArticleClick(article) {
      console.log('点击帖子:', article)
      
      if (!article || !article.id) {
        uni.showToast({
          title: '帖子信息不完整',
          icon: 'none'
        })
        return
      }

      uni.navigateTo({
        url: `/pages/test01/test01?id=${article.id}&userId=${this.userId}`,
        success: (res) => {
          console.log('跳转成功')
        },
        fail: (err) => {
          console.error('跳转失败:', err)
          uni.showToast({
            title: '页面跳转失败',
            icon: 'none'
          })
        }
      })
    },

    onGridItemClick(item) {
      if (item.path) {
        uni.navigateTo({
          url: item.path,
          fail: (err) => {
            console.error('页面跳转失败:', err);
            uni.showToast({
              title: '页面跳转失败',
              icon: 'none'
            });
          }
        });
      } else {
        uni.showToast({ 
          title: `点击了${item.text}`, 
          icon: 'none' 
        });
      }
    },

    getUserArticles() {
      postApi.myselectall().then(res => {
        if (res && res.data) {
          this.articles = res.data.map(item => {
            // 添加调试日志
            console.log('文章数据:', item);
            console.log('imageId类型:', typeof item.imageId);
            
            // 处理图片数据
            let images = [];
            if (item.imageId) {
              // 如果 imageId 已经是数组，直接使用
              if (Array.isArray(item.imageId)) {
                images = item.imageId;
              } 
              // 如果是字符串，尝试分割
              else if (typeof item.imageId === 'string') {
                images = item.imageId.split(',').filter(img => img);
              }
              // 如果是单个图片URL
              else {
                images = [item.imageId];
              }
            }

            return {
              id: item.id,
              content: item.text,
              title: item.tittle,
              postTime: this.formatTime(item.startingTime),
              images: images,
              likes: 0,
              comments: 0,
              userId: item.userId
            };
          });
          
          // 调试输出处理��的数据
          console.log('处理后的文章数据:', this.articles);
        } else {
          this.articles = [];
        }
      }).catch(err => {
        console.error('获取文章列表失败:', err);
        uni.showToast({
          title: '获取文章列表失败',
          icon: 'none'
        });
      });
    },

    formatTime(timestamp) {
      if (!timestamp) return ''
      const date = new Date(timestamp)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hour = String(date.getHours()).padStart(2, '0')
      const minute = String(date.getMinutes()).padStart(2, '0')
      
      return `${year}-${month}-${day} ${hour}:${minute}`
    },

    handleImageError(e) {
      console.error('图片加载失败:', e);
      // 可以在这里设置一个默认图片
      const defaultImage = '/static/default-image.png';
      if (e.target && e.target.dataset) {
        // 获取当前图片的索引，并替换为默认图片
        const index = e.target.dataset.index;
        if (typeof index !== 'undefined') {
          this.$set(this.articles[index].images, index, defaultImage);
        }
      }
    },

    // 添加头像加载错误处理
    handleAvatarError(e) {
      console.error('头像加载失败，详细信息:', {
        currentUrl: this.imgurl,
        error: e.detail
      })
      
      // 尝试使用临时文件路径
      if (this.imgurl && this.imgurl.startsWith('http')) {
        uni.downloadFile({
          url: this.imgurl,
          success: (res) => {
            if (res.statusCode === 200) {
              console.log('下载头像成功，临时路径:', res.tempFilePath)
              this.imgurl = res.tempFilePath
            } else {
              console.error('下载头像失败，状态码:', res.statusCode)
              this.imgurl = '/static/avatar.png'
            }
          },
          fail: (err) => {
            console.error('下载头像失败:', err)
            this.imgurl = '/static/avatar.png'
          }
        })
      } else {
        this.imgurl = '/static/avatar.png'
      }
      
      uni.showToast({
        title: '头像加载失败',
        icon: 'none'
      })
    },

    // 添加删除文章的方法
    handleDeleteArticle(articleId) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这篇文章吗？',
        success: (res) => {
          if (res.confirm) {
            this.deleteArticle(articleId);
          }
        }
      });
    },

    // 执行删除文章的操作
    async deleteArticle(articleId) {
      try {
        uni.showLoading({
          title: '删除中...'
        });
        
        console.log('准备删除文章，ID:', articleId);
        
        // 直接传 ID
        const response = await postApi.deletePost(articleId);

        console.log('删除响应:', response);

        if (response && response.code === 1) {
          uni.showToast({
            title: '删除成功',
            icon: 'success'
          });
          
          // 重新获取文章列表
          this.getUserArticles();
        } else {
          throw new Error(response.msg || '删除失败');
        }
      } catch (error) {
        console.error('删除文章失败:', error);
        uni.showToast({
          title: error.message || '删除失败',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    },

    // 添加跳转方法
    goToClubRegister() {
      uni.navigateTo({
        url: '/pages/mine/club'
      });
    }
  }
}
</script>

<style scoped>
	.articles-section {
	  margin-top: 20px;
	}
	
	.article-item {
	  background: #ffffff;
	  border-radius: 10px;
	  padding: 15px;
	  margin-bottom: 15px;
	  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
	}
	
	.article-content {
	  font-size: 14px;
	  color: #333;
	  margin-bottom: 10px;
	}
	
	.article-images {
	  display: flex;
	  flex-wrap: wrap;
	  gap: 8px;
	  margin-bottom: 10px;
	}
	
	.article-image {
	  width: 100px;
	  height: 100px;
	  border-radius: 8px;
	}
	
	.article-footer {
	  display: flex;
	  justify-content: space-between;
	  align-items: center;
	  font-size: 12px;
	  color: #999;
	}
	
	.article-stats {
	  display: flex;
	  gap: 15px;
	}
	.profile-section {
	  /* 保留原有样式 */
	  cursor: pointer; /* 显示手型光标 */
	}
	
	.profile-section:active {
	  opacity: 0.8; /* 点击时略微降低透明度 */
	}
	
.personal-center {
  padding: 20px;
  background: linear-gradient(to bottom, #e0f7fa, #80deea);
  min-height: 100vh;
  box-sizing: border-box;
}

.profile-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
}

.avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  border: 4px solid #ffffff;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.nickname {
  margin-top: 10px;
  font-size: 18px;
  font-weight: bold;
  color: #00796b;
}

.grid-section {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 15px;
  margin-bottom: 20px;
}

.grid-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #ffffff;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 15px;
  transition: transform 0.2s;
}

.grid-item:active {
  transform: scale(0.95);
}

.grid-icon {
  width: 40px;
  height: 40px;
  margin-bottom: 8px;
}

.grid-text {
  font-size: 14px;
  color: #555555;
}

.ad-section {
  margin-top: 20px;
  padding: 15px;
  background: #ffffff;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.ad-image {
  width: 100%;
  border-radius: 8px;
}

/* 新增文章列表样式 */
.article-list {
  margin: 0;
  padding: 0;
  width: 100%;
}

.article-item {
  margin-bottom: 10rpx;
  padding: 0;
  background-color: #fff;
  width: 100%;
}

.no-login-tip, .empty-tip {
  text-align: center;
  padding: 40rpx;
  color: #999;
  font-size: 28rpx;
}

.article-content {
  margin: 0;
  width: 100%;
}

.article-text {
  font-size: 28rpx;
  color: #333;
  line-height: 1.6;
  padding: 20rpx;
}

.single-image {
  width: 100%;
  max-height: 400rpx;
}

.image-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 4rpx;
  width: 100%;
}

.image-grid image {
  width: 200rpx;
  height: 200rpx;
  border-radius: 8rpx;
  object-fit: cover;
}

.article-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  border-top: 1rpx solid #f5f5f5;
}

.post-time {
  font-size: 24rpx;
  color: #999;
}

.article-actions {
  display: flex;
  align-items: center;
}

.action-item {
  display: flex;
  align-items: center;
  margin-left: 30rpx;
}

.action-item image {
  width: 32rpx;
  height: 32rpx;
  margin-right: 8rpx;
}

.action-item text {
  font-size: 24rpx;
  color: #666;
}

.article-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  position: relative;
  padding: 20rpx;
}

.delete-article-btn {
  position: absolute;
  right: 20rpx;
  top: 20rpx;
  background-color: #ff4d4f;
  color: #fff;
  padding: 4rpx 16rpx;
  border-radius: 24rpx;
  font-size: 24rpx;
  z-index: 1;
}

.delete-article-btn:active {
  opacity: 0.8;
}

/* 确保文章文本不会被删除按钮遮挡 */
.article-text {
  flex: 1;
  margin-right: 80rpx;
}

/* 添加菜单项样式 */
.menu-item {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 2rpx;
}

.menu-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.menu-text {
  font-size: 28rpx;
  color: #333;
}

.icon-arrow-right {
  color: #999;
  font-size: 24rpx;
}
</style>
